package com.wtao.healthy.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.wtao.healthy.entity.UseDate;
import com.wtao.healthy.entity.User;
import com.wtao.healthy.service.IUseDateService;
import com.wtao.healthy.service.IUserService;
import com.wtao.healthy.util.SendMsgUtil;
import com.wtao.healthy.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.scheduling.annotation.Scheduled;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Configuration
@Slf4j
public class DayTask {

    @Autowired
    private IUserService userService;
    @Autowired
    private IUseDateService useDateService;

    public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");

    @Scheduled(cron = "0 0 9,19 * * ? ")
    public void dayTask() throws ParseException {
        String currentDay = DATE_FORMAT.format(new Date());
        log.info("当前时间是:{}", currentDay);
        LambdaQueryWrapper<UseDate> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UseDate::getUseDate,currentDay);
        List<UseDate> list = useDateService.list(lambdaQueryWrapper);

        List<Long> userIds = list.stream().map(UseDate::getUserId).collect(Collectors.toList());
        List<User> users = userService.getBaseMapper().selectBatchIds(userIds);

        StringBuilder sb = new StringBuilder();
        sb.append("今天是：" + currentDay + "\r\n");
        sb.append("需要提醒的人有:[");
        for (int i = 0; i < users.size(); i++) {
            if (i != 0) {
                sb.append("、");
            }
            sb.append( users.get(i).getName() + ":" + "第" + list.get(i).getTimes() + "次使用");
        }
        sb.append("]");
        String msg = sb.toString();
        SendMsgUtil.mySend("18211036881", msg);
        log.info("已经发送短信,内容为:{}", msg);
    }

}
